package com.watson.activity;

import static com.watson.fragment.HomeFragment.U_DEPOT_ID;

import android.app.Dialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.widget.NestedScrollView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.watson.Base2Activity;
import com.watson.LoginActivity;
import com.watson.MyApp;
import com.watson.R;
import com.watson.adapter.Details2Adapter;
import com.watson.adapter.TakeCodeAdapter;
import com.watson.http.CommonHttpConsts;
import com.watson.http.HttpCallbackData;
import com.watson.http.HttpClient;
import com.watson.utils.DialogUitl;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;
import com.watson.utils.StringUtils;
import com.watson.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class TaskDetailsActivity extends Base2Activity {
    private DrawerLayout mDrawerLayout;
    private RelativeLayout mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private TextView tvTitle, tvbillsort, tvTime, tvout_storage, tvStatus;
    private AppCompatButton btnKu, btnBack, btnClaim, btnWithdraw, btnCancellation;
    private RelativeLayout lyInside;
    private LinearLayout lySan;
    private ImageView imgSan;
    private String noId, zt;
    private RecyclerView recyclerData;
    private Details2Adapter detailsAdapter;
    private Map dataList;
    private ArrayList<Map> detailsList;
    private NestedScrollView sNestedScrollView;
    private ArrayList<Map> codelist;
    private int num;
    private String R_Auth_Code = "";
    private MediaPlayer mediaPlayer;
    private int standing;
    private int statuscode = 99;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details2);
        statusbar4();
        mDrawerLayout = findViewById(R.id.drawer_layout);
        mDrawerList = findViewById(R.id.left_drawer);
        num = 0;
        dataList = new HashMap();
        detailsList = new ArrayList<>();
        codelist = new ArrayList<>();
        noId = getIntent().getStringExtra("no");
        LogUtils.e("TAG", "--------->" + noId);
        zt = getIntent().getStringExtra("zt");
        R_Auth_Code = SPUtils.get(mContext, "auth", "") + "";
        standing = StringUtils.isEmpty(SPUtils.get(mContext, "standing", "") + "") ? -1 : Integer.valueOf(SPUtils.get(mContext, "standing", "") + "");
        initView();
        initClick();
        get_WMS_WarehouseEntryTaskDetails(noId, zt);
        MyApp.setOnImportListener(new MyApp.OnImportListener() {
            @Override
            public void showToastMessage(String message) {
                LogUtils.e("TAG", "message=========>" + message);
                if (R_Auth_Code.contains("WMS_TASK_IN_BTN")) {
                    if (!dataList.isEmpty()) {
                        String taskrecipientid = dataList.get("taskrecipientid") + "";
                        if (taskrecipientid.equals(SPUtils.get(mContext, "U_Id", "") + "") || (standing == 1)) {
                            if (statuscode == 2) {
                                if (message.contains("K:") && kuContent != null) {
                                    kuContent.setText(message.replace("K:", "") + "");
                                    ts_cg();
                                } else {
                                    if (codelist.size() < num) {
                                        rule(message, null);
                                    } else {
                                        ts_cw();
                                        tiDialog("以达到数量，请核查！");
                                    }
                                }
                            }
                        } else {
                            //statuscode 0：未领取  2：入库中 3：已完成 -1：作废
                            //0 ：只能领单，2：可以作废、确认入库 正常扫码  3：只能看 -1：只能看
                            ts_cw();
//                            tiDialog("非个人任务，请核查！");
                        }
                    }
                }
            }
        });
    }

    private void rule(String scanStr, AlertDialog dialog) {
        LogUtils.e("TAG", "scanStr:" + scanStr);
        String liu = "";
        String ri = "";
        String gong = "";
        String bian = "";
        boolean isData = false;

        int overTime = 0;
        ArrayList<Map> numberRuleList = new ArrayList<>();
        numberRuleList = (ArrayList<Map>) JSON.parseArray(SPUtils.get(mContext, "numberRuleList", "") + "", Map.class);
        LogUtils.e("TAG", "numberRuleList:" + numberRuleList.toString());
        String text = "识别码有误，请检查！";
        if (numberRuleList.size() > 0) {
            int EngineCodeLenth = 0;
            int Priority = 0;
            int TypeCodeLenth = 0;
            int TypeCodeIndex = 0;
            int DateCodingLenth = 0;
            int DateCodingIndex = 0;//A126061225430102024
            int FactoryCodeLenth = 0;
            int FactoryCodeIndex = 0;
            int SerialNumberLenth = 0;
            int SerialNumberIndex = 0;
            int IsUsable;
            if (scanStr.length() > 0) {
                for (int i = 0; i < numberRuleList.size(); i++) {
                    EngineCodeLenth = Integer.valueOf(numberRuleList.get(i).get("EngineCodeLenth") + "");
                    LogUtils.e("TAG", "EngineCodeLenth:" + EngineCodeLenth + ",,,," + scanStr.length());
                    if (EngineCodeLenth == scanStr.length()) {
                        EngineCodeLenth = Integer.valueOf(numberRuleList.get(i).get("EngineCodeLenth") + "");
                        TypeCodeLenth = Integer.valueOf(numberRuleList.get(i).get("TypeCodeLenth") + "");
                        TypeCodeIndex = Integer.valueOf(numberRuleList.get(i).get("TypeCodeIndex") + "");
                        DateCodingLenth = Integer.valueOf(numberRuleList.get(i).get("DateCodingLenth") + "");
                        DateCodingIndex = Integer.valueOf(numberRuleList.get(i).get("DateCodingIndex") + "");
                        FactoryCodeLenth = Integer.valueOf(numberRuleList.get(i).get("FactoryCodeLenth") + "");
                        FactoryCodeIndex = Integer.valueOf(numberRuleList.get(i).get("FactoryCodeIndex") + "");
                        SerialNumberLenth = Integer.valueOf(numberRuleList.get(i).get("SerialNumberLenth") + "");
                        SerialNumberIndex = Integer.valueOf(numberRuleList.get(i).get("SerialNumberIndex") + "");
                        IsUsable = Integer.valueOf(numberRuleList.get(i).get("IsUsable") + "");

                        String time = numberRuleList.get(i).get("OverTime") + "";
                        if (!StringUtils.isEmpty(time)) {
                            overTime = Integer.valueOf(time.replaceFirst("^0+(?!$)", ""));
                        } else {
                            overTime = 0;
                        }


                        liu = scanStr.substring(TypeCodeIndex, TypeCodeIndex + TypeCodeLenth);
                        ri = scanStr.substring(DateCodingIndex, DateCodingIndex + DateCodingLenth);
                        gong = scanStr.substring(FactoryCodeIndex, FactoryCodeIndex + FactoryCodeLenth);
                        bian = scanStr.substring(SerialNumberIndex, SerialNumberIndex + SerialNumberLenth);

                        int jjj = 0;
                        if (StringUtils.isNumeric(ri)) {
                            jjj = Integer.valueOf(ri);
                        }

                        LogUtils.e("TAG", "liu:" + liu);
                        LogUtils.e("TAG", "ri:" + ri);
                        LogUtils.e("TAG", "gong:" + gong);
                        LogUtils.e("TAG", "bian:" + bian);

                        if (overTime == 0 || jjj < overTime) {
                            ArrayList<Map> detailsList = new ArrayList<>();
                            detailsList = (ArrayList<Map>) JSON.parseArray(dataList.get("details") + "", Map.class);
                            LogUtils.e("TAG", "detailsList:" + detailsList.toString());
                            for (int k = 0; k < detailsList.size(); k++) {
                                ArrayList<Map> codesupplierList = new ArrayList<>();
                                codesupplierList = (ArrayList<Map>) JSON.parseArray(detailsList.get(k).get("codesupplierList") + "", Map.class);
                                LogUtils.e("TAG", "codesupplierList:" + codesupplierList.toString());
                                for (int j = 0; j < codesupplierList.size(); j++) {
                                    String code = codesupplierList.get(j).get("code") + "";
                                    String supplier = codesupplierList.get(j).get("supplier") + "";
                                    if (code.equals(liu) && supplier.equals(gong)) {
                                        int codes = 0;
                                        if (codelist.size() > 0) {
                                            for (int ii = 0; ii < codelist.size(); ii++) {
                                                if (codelist.get(ii).get("erpno").toString().contains(detailsList.get(k).get("erpno") + "")) {
                                                    codes = codes + 1;
                                                }
                                            }
                                        }

                                        int num = StringUtils.isEmpty(detailsList.get(k).get("num") + "") ? 0 : Integer.valueOf(detailsList.get(k).get("num") + "");

                                        if (codes >= num) {
                                            isData = false;
                                            tiDialog("以达到拣货数量，请检查！");
                                            ts_cw();
                                            return;
                                        } else {
                                            isData = true;

                                            Map data = new HashMap();
                                            data.put("billno", dataList.get("lastbillno"));
                                            data.put("scaningtime", StringUtils.getTimeS());
                                            data.put("scanner", SPUtils.get(mContext, "U_Name", ""));
                                            data.put("scannerid", SPUtils.get(mContext, "U_Id", ""));
                                            data.put("sn", StringUtils.getDeviceSN(mContext));
                                            data.put("erpno", detailsList.get(k).get("erpno"));
                                            data.put("motorid", scanStr);
                                            data.put("no", dataList.get("no"));
                                            data.put("std", detailsList.get(k).get("std"));
//                                    data.put("fid", dataList.get("fid"));

                                            data.put("name", detailsList.get(k).get("name"));
                                            data.put("brand", detailsList.get(k).get("brand") + "");
                                            data.put("car", codesupplierList.get(j).get("car"));

                                            LogUtils.e("TAG", "data:" + data.toString());
                                            if (!codelist.toString().contains(scanStr)) {
                                                codelist.add(data);
                                                ToastUtil.show("扫码添加成功");
                                            } else {
                                                text = "识别码已添加，请检查！";
                                                isData = false;
                                            }

                                            LogUtils.e("TAG", "codelist:" + codelist.toString());

                                            detailsAdapter.setCode(codelist);
                                            codeAdapter.setData(codelist);
                                            tvNum.setText("（" + codelist.size() + "）");

                                            if (isData) {
                                                ts_cg();
                                            } else {
                                                tiDialog(text);
                                                ts_cw();
                                            }

                                            cun();

                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            tiDialog("识别码有误,请检查");
            ts_cw();

            if (dialog != null) {
                dialog.dismiss();
            }
        } else {
            tiDialog("未检测到匹配规则,请重新登录");
            ts_cw();
        }
    }

    private AlertDialog tiDialogs;

    public void tiDialog(String text) {
        if (tiDialogs != null) {
            tiDialogs.dismiss();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_ti, null);
        TextView tvSave = v.findViewById(R.id.tvSave);
        TextView tvName = v.findViewById(R.id.tvNames);
        tiDialogs = builder.create();
        tiDialogs.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!tiDialogs.isShowing()) {//此时提示框未显示
            tiDialogs.show();
        }
        tiDialogs.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        tiDialogs.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        tvName.setText(text);
        //自定义的东西
        tiDialogs.getWindow().setContentView(v);
        tvSave.setOnClickListener(view -> tiDialogs.dismiss());
    }

    public void ts_cg() {
        TaskDetailsActivity.this.runOnUiThread(() -> {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            mediaPlayer = MediaPlayer.create(mContext, R.raw.ts_cg);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.start();
        });
    }

    public void ts_cw() {
        TaskDetailsActivity.this.runOnUiThread(() -> {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            mediaPlayer = MediaPlayer.create(mContext, R.raw.ts_cw);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.start();
        });
    }

    private void initClick() {
        findViewById(R.id.imgBack).setOnClickListener(v -> {
            if (R_Auth_Code.contains("WMS_TASK_IN_BTN")) {
                if (codelist.size() > 0 && !dataList.isEmpty()) {
                    String taskrecipientid = dataList.get("taskrecipientid") + "";
                    if (statuscode == 2 && (taskrecipientid.equals(SPUtils.get(mContext, "U_Id", "") + "") || standing == 1)) {
                        if (!dataList.isEmpty()) {
                            cun();
                        }

                        Intent data = new Intent();
                        data.putExtra("name", true);
                        setResult(RESULT_OK, data);
                        finish();
                    } else {
                        finish();
                    }
                } else {
                    finish();
                }
            } else {
                finish();
            }
        });

        btnWithdraw.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            exitDialog(1, null);
        });

        btnCancellation.setOnClickListener(v -> {
//            if (StringUtils.isFastClick()) {
//                return;
//            }
            exitDialog(0, null);
        });

        btnKu.setOnClickListener(v -> {
//            if (StringUtils.isFastClick()) {
//                return;
//            }
            LogUtils.e("TAG", "num:" + num);
            LogUtils.e("TAG", "codelist.size():" + codelist.size());
            if (codelist.size() > 0 && !dataList.isEmpty() && codelist.size() == num) {
                if (R_Auth_Code.contains("IsWarehouseEntry")) {
                    kuweiDialog();
                } else {
                    exitDialog(4, null);
                }
            } else {
                ToastUtil.show("扫码数据小于单据数量，请检查！");
            }
        });

        btnBack.setOnClickListener(v -> {
            //出库之后，当发现产品破损，可返回打包状态
            if (StringUtils.isFastClick()) {
                return;
            }
            exitDialog(3, null);
        });
        btnClaim.setOnClickListener(v -> {
//            if (StringUtils.isFastClick()) {
//                return;
//            }
            if (!dataList.isEmpty()) {
                exitDialog(5, null);
            }
        });
    }

    private void add_WMS_WarehouseEntryTask(String no, String sn) {
        Map data = new HashMap();
        data.put("no", noId);
        data.put("sn", sn);
        data.put("taskrecipient", SPUtils.get(mContext, "U_Name", "") + "");
        data.put("taskrecipientid", SPUtils.get(mContext, "U_Id", "") + "");//任务领取人id
        data.put("wh", U_DEPOT_ID + "");//作业仓库
        if (R_Auth_Code.contains("WMS_IN_SCAN_ClAIMTICKET")) {
            data.put("authcode", "WMS_IN_SCAN_ClAIMTICKET");
        } else {
            data.put("authcode", "");
        }
        String datStr = new Gson().toJson(data);
        HttpClient.getInstance().postData(CommonHttpConsts.add_WMS_WarehouseEntryTask, "add_WMS_WarehouseEntryTask")
                .headers("token", SPUtils.get(mContext, "token", "") + "")
                .upJson(datStr)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        ToastUtil.show(msg);
                        if (code == 1001) {
                            ts_cg();
                            get_WMS_WarehouseEntryTaskDetails(noId, zt);
                        } else {
                            ts_cw();
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (R_Auth_Code.contains("WMS_TASK_IN_BTN")) {
                if (codelist.size() > 0 && !dataList.isEmpty()) {
                    String taskrecipientid = dataList.get("taskrecipientid") + "";
                    if (statuscode == 2 && (taskrecipientid.equals(SPUtils.get(mContext, "U_Id", "") + "") || standing == 1)) {
                        if (!dataList.isEmpty()) {
                            cun();
                        }
                        return super.onKeyDown(keyCode, event);
                    } else {
                        return super.onKeyDown(keyCode, event);
                    }
                } else {
                    return super.onKeyDown(keyCode, event);
                }
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exitDialog(int type, AlertDialog kuDialog) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_exit, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvName = v.findViewById(R.id.tvName);
        TextView tvSave = v.findViewById(R.id.tvSave);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        if (type == 1) {
            tvName.setText("确认撤销订单吗");
        }
        if (type == 0) {
            tvName.setText("确认作废订单吗");
        }
        if (type == 3) {
            tvName.setText("确认返回打包吗");
        }
        if (type == 4) {
            tvName.setText("确认完成吗");//验单
        }
        if (type == 5) {
            tvName.setText("确认领单吗");
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());

        tvSave.setOnClickListener(view -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            if (type == 1 || type == 0) {
                delete_WMS_WarehouseEntryTask(type);
            }
            if (type == 3) {
                if (!dataList.isEmpty()) {
                    update_WMS_ReturnPacking(dataList.get("no") + "");
                }
            }
            if (type == 4) {
                insert_WMS_WarehouseEntry_ScanCodeRecord(dataList.get("no") + "", kuDialog);
            }
            if (type == 5) {
                add_WMS_WarehouseEntryTask(dataList.get("no") + "", StringUtils.getDeviceSN(mContext));
            }
            dialog.dismiss();
        });
    }

    private void initView() {
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText("详情");
        lyInside = findViewById(R.id.lyInside);
        lySan = findViewById(R.id.lySan);
        lySan.setVisibility(View.GONE);
        tvStatus = findViewById(R.id.tvStatus);
        recyclerData = findViewById(R.id.recyclerData);
        recyclerData.setLayoutManager(new LinearLayoutManager(mContext));
        detailsAdapter = new Details2Adapter(mContext, detailsList);
        recyclerData.setAdapter(detailsAdapter);
        detailsAdapter.setItemClickListener(new Details2Adapter.ItemClickListener() {
            @Override
            public void onClick(int position, ArrayList<Map> mList) {

            }

            @Override
            public void onBClick(int position) {
                if (R_Auth_Code.contains("WMS_TASK_SDLR")) {
                    editDialog(position);
                }
            }
        });
        tvbillsort = findViewById(R.id.tvbillsort);
        tvout_storage = findViewById(R.id.tvout_storage);
        tvTime = findViewById(R.id.tvTime);
        btnKu = findViewById(R.id.btnKu);
        btnBack = findViewById(R.id.btnBack);
        btnClaim = findViewById(R.id.btnClaim);
        btnWithdraw = findViewById(R.id.btnWithdraw);
        btnCancellation = findViewById(R.id.btnCancellation);
        sNestedScrollView = findViewById(R.id.sNestedScrollView);
        sNestedScrollView.post(() -> sNestedScrollView.fullScroll(ScrollView.FOCUS_UP));
        recyclerCode = findViewById(R.id.recyclerCode);
        tvNum = findViewById(R.id.tvNum);
        imgSan = findViewById(R.id.imgSan);
        imgSan.setVisibility(View.GONE);

        recyclerCode.setLayoutManager(new LinearLayoutManager(mContext));
        codeAdapter = new TakeCodeAdapter(mContext, codelist);
        recyclerCode.setAdapter(codeAdapter);
        if (!dataList.isEmpty()) {
            codeAdapter.setDataList(detailsList);
        }
        codeAdapter.setItemClickListener((position, mList) -> {
            codelist.remove(position);

            codeAdapter.setData(codelist);
            detailsAdapter.setCode(codelist);
            tvNum.setText("（" + codelist.size() + "）");

            cun();
        });
        tvNum.setText("（" + codelist.size() + "）");
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerLayout.closeDrawer(mDrawerList);
        findViewById(R.id.tvSideslip).setOnClickListener(v -> mDrawerLayout.openDrawer(mDrawerList));

        imgSan.setOnClickListener(v -> lySan.setVisibility(View.VISIBLE));
        lySan.setOnClickListener(v -> lySan.setVisibility(View.GONE));
    }

    private void setView(Map map) {
//        if (map.containsKey("isupdate")) {//1线上，0本地
//            int isupdate = StringUtils.isEmpty(map.get("isupdate") + "") ? 0 : Integer.valueOf(map.get("isupdate") + "");
//            if (isupdate == 1) {
//                cun();
//            }
//            if (isupdate == 0) {
        if (!dataList.isEmpty()) {
            String cdNo = SPUtils.get(mContext, "cd_" + dataList.get("fid"), "") + "";
            LogUtils.e("TAG", "cdNo--->:" + cdNo);
            if (!StringUtils.isEmpty(cdNo)) {
                Map dataCode = new HashMap();
                dataCode = JSON.parseObject(SPUtils.get(mContext, "cd_" + dataList.get("fid"), "") + "", Map.class);
                codelist = new ArrayList<>();
                codelist = (ArrayList<Map>) JSON.parseArray(dataCode.get("wMS_CodeScanningRecord") + "", Map.class);
                codeAdapter.setDataList(detailsList);
                detailsAdapter.setCode(codelist);
            }

            num = 0;
            for (int i = 0; i < detailsList.size(); i++) {
                String n = detailsList.get(i).get("num") + "";
                if (!StringUtils.isEmpty(n)) {
                    num = num + Integer.valueOf(n);
                }
            }
        }
//            }
//        }

        tvbillsort.setText(map.get("billsort") + "");
        tvout_storage.setText(StringUtils.isEmpty(map.get("in_storage") + "") ? "" : map.get("in_storage") + "");
        tvTime.setText(map.get("lastbillsort") + "-" + map.get("lastbillno"));
        btnClaim.setVisibility(View.GONE);
        btnKu.setVisibility(View.GONE);
        btnBack.setVisibility(View.GONE);
        btnWithdraw.setVisibility(View.GONE);
        btnCancellation.setVisibility(View.GONE);
        imgSan.setVisibility(View.GONE);
        String taskrecipient = map.get("taskrecipient") + "";
        if (!StringUtils.isEmpty(taskrecipient)) {
            tvTitle.setText("详情(" + taskrecipient.trim() + ")");
        }
        String taskrecipientid = map.get("taskrecipientid") + "";
        //statuscode 0：未领取  2：入库中 3：已完成 -1：作废
        //0 ：只能领单，2：可以作废、确认入库 正常扫码  3：只能看 -1：只能看
        String taskstatus = StringUtils.isEmpty(map.get("taskstatus") + "") ? "" : map.get("taskstatus") + "";
        if (map.containsKey("statuscode")) {
            statuscode = Integer.valueOf(StringUtils.isEmpty(map.get("statuscode") + "") ? "99" : map.get("statuscode") + "");//单据状态
        } else {
            if (taskstatus.equals("未领取")) {
                statuscode = 0;
            } else if (taskstatus.equals("入库中")) {
                statuscode = 2;
            } else if (taskstatus.equals("已完成")) {
                statuscode = 3;
            } else if (taskstatus.equals("作废")) {
                statuscode = -1;
            }
        }
        LogUtils.e("TAG", "statuscode:" + statuscode);
        tvStatus.setText(StringUtils.isEmpty(map.get("taskstatus") + "") ? "" : map.get("taskstatus") + "");
        //任务的状态：进行中  已完成   暂存  作废（作废单据不会返回给app端）
        if (statuscode == 0) {
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status1));
        } else if (statuscode == 2) {
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status2));
        } else if (statuscode == 3) {
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.tv333));
        } else {
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.gray));
        }

        LogUtils.e("TAG", "R_Auth_Code:" + R_Auth_Code.toString());
        if (R_Auth_Code.contains("ADD_WarehouseEntryTask") && statuscode == 0) {
            //领单
            btnClaim.setVisibility(View.VISIBLE);
            btnClaim.setText("领单");
        } else {
            btnClaim.setVisibility(View.GONE);
        }
        if (R_Auth_Code.contains("WMS_TASK_IN_BTN") && statuscode == 2
                && (taskrecipientid.equals(SPUtils.get(mContext, "U_Id", "") + "") || (standing == 1))) {
            //入库
            btnKu.setText("完成");
            btnKu.setVisibility(View.VISIBLE);
        } else {
            btnKu.setVisibility(View.GONE);
        }
        if (R_Auth_Code.contains("DEL_WarehouseEntryTask") && statuscode == 2
                && (taskrecipientid.equals(SPUtils.get(mContext, "U_Id", "") + "") || (standing == 1))) {
            //作废
            btnCancellation.setVisibility(View.VISIBLE);
            imgSan.setVisibility(View.VISIBLE);
        } else {
            imgSan.setVisibility(View.GONE);
            btnCancellation.setVisibility(View.GONE);
        }
        LogUtils.e("TAG", "R_Auth_Code---->:" + (!R_Auth_Code.contains("WMS_TASK_FH")));

        codeAdapter.setData(codelist);
        if (!dataList.isEmpty()) {
            codeAdapter.setDataList(detailsList);
            LogUtils.e("TAG", dataList.get("taskrecipientid") + ",,,,,,," + dataList.get("taskstatus") + ",,," + SPUtils.get(mContext, "U_Id", ""));
            LogUtils.e("TAG", "----" + taskrecipientid.trim().equals(SPUtils.get(mContext, "U_Id", "") + ""));
            codeAdapter.setTask(dataList.get("taskrecipientid") + "", dataList.get("taskstatus") + "");
        }
        tvNum.setText("（" + codelist.size() + "）");
    }

    private RecyclerView recyclerCode;
    private TextView tvNum;
    private TakeCodeAdapter codeAdapter;

    private void get_WMS_WarehouseEntryTaskDetails(String id, String zt) {
        HttpClient.getInstance().getData(CommonHttpConsts.get_WMS_WarehouseEntryTaskDetails, "get_WMS_WarehouseEntryTaskDetails")//
                .headers("token", SPUtils.get(mContext, "token", "") + "").params("no", id + "")//单号
//                .params("zt", zt)//单据归属
                .execute(new HttpCallbackData() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 && !StringUtils.isEmpty(info)) {

                            dataList = JSON.parseObject(info, Map.class);
                            LogUtils.e("TAG", "dataList:" + dataList.toString());
                            if (!dataList.isEmpty()) {
                                ArrayList<Map> list = new ArrayList<>();
                                codelist = new ArrayList<>();
                                String codelistStr = dataList.get("codelists") + "";
                                if (codelistStr.length() > 10) {
                                    codelist = (ArrayList<Map>) JSON.parseArray(dataList.get("codelists") + "", Map.class);
                                    detailsAdapter.setCode(codelist);
                                }
                                if (StringUtils.isEmpty(dataList.get("details") + "")) {
                                    ToastUtil.show("数据异常，请重试");
                                    return;
                                }
                                detailsList = (ArrayList<Map>) JSON.parseArray(dataList.get("details") + "", Map.class);
                                LogUtils.e("TAG", "codelistStr:" + codelistStr);

                                LogUtils.e("TAG", "dataList:" + dataList.toString());
                                detailsAdapter.setData(detailsList);
                                detailsAdapter.setBillstatus(dataList.get("taskstatus") + "", dataList.get("taskrecipientid") + "");

                                setView(dataList);
                            }
                        } else {
                            ToastUtil.show(msg);
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    private void delete_WMS_WarehouseEntryTask(int type) {
        Map data = new HashMap();
        data.put("no", noId);
//        data.put("type", type);//0作废，1撤单
        String datStr = new Gson().toJson(data);
        HttpClient.getInstance().getData(CommonHttpConsts.delete_WMS_WarehouseEntryTask, "delete_WMS_WarehouseEntryTask").headers("token", SPUtils.get(mContext, "token", "") + "").params("no", noId).execute(new HttpCallbackData() {

            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                ToastUtil.show(msg);
                if (code == 1001) {
                    ts_cg();
                    SPUtils.remove(mContext, "cd_" + dataList.get("fid"));
                    Intent data = new Intent();
                    data.putExtra("name", true);
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    ts_cw();
                }
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }
        });
    }

    private void update_WMS_ReturnPacking(String no) {
        HttpClient.getInstance().getData(CommonHttpConsts.update_WMS_ReturnPacking, "update_WMS_ReturnPacking").headers("token", SPUtils.get(mContext, "token", "") + "").params("no", no).execute(new HttpCallbackData() {

            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                ToastUtil.show(msg);
                if (code == 1001) {
                    get_WMS_WarehouseEntryTaskDetails(no, zt);
                }
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }
        });
    }

    private void cun() {
        ArrayList<Map> wMS_CodeScanningRecord = new ArrayList<>();
        for (int i = 0; i < codelist.size(); i++) {
            Map data = new HashMap();
            data.put("billno", codelist.get(i).get("billno"));
            data.put("scaningtime", codelist.get(i).get("scaningtime"));
            data.put("scanner", codelist.get(i).get("scanner"));
            data.put("scannerid", codelist.get(i).get("scannerid"));
            data.put("sn", codelist.get(i).get("sn"));
            data.put("erpno", codelist.get(i).get("erpno"));
            data.put("motorid", codelist.get(i).get("motorid"));
            data.put("no", codelist.get(i).get("no"));
            data.put("std", codelist.get(i).get("std"));
            if (codelist.get(i).containsKey("id")) {
                data.put("id", codelist.get(i).get("id"));
            }
            if (codelist.get(i).containsKey("insertTime")) {
                data.put("insertTime", codelist.get(i).get("insertTime"));
            }

            wMS_CodeScanningRecord.add(data);
        }
        Gson gson = new Gson();
        JSONObject jsonObject = new JSONObject();
        String code = "";
        String car = "";
        String supplier = "";
        if (detailsList.size() > 0) {
            code = detailsList.get(0).get("code") + "";
            car = detailsList.get(0).get("car") + "";
            ArrayList<Map> codesupplierList = new ArrayList<>();
            codesupplierList = (ArrayList<Map>) JSON.parseArray(detailsList.get(0).get("codesupplierList") + "", Map.class);
            if (codesupplierList.size() > 0) {
                supplier = codesupplierList.get(0).get("supplier") + "";
                if (StringUtils.isEmpty(code)) {
                    code = codesupplierList.get(0).get("code") + "";
                }
                if (StringUtils.isEmpty(car)) {
                    car = codesupplierList.get(0).get("car") + "";
                }
            }
        }
        jsonObject.put("no", dataList.get("no"));
        jsonObject.put("type", 2);//类型 1确认出库 2暂存数据
        jsonObject.put("billno", dataList.get("no") + "");
        jsonObject.put("code", code);
        jsonObject.put("car", car);
        jsonObject.put("isType", 1);
        jsonObject.put("supplier", supplier);
        jsonObject.put("wMS_CodeScanningRecord", wMS_CodeScanningRecord);
        String datStr = gson.toJson(jsonObject);
        datStr = datStr.replaceAll("\\\\", "").trim();

        LogUtils.e("TAG", "datStr:" + datStr);

        SPUtils.put(mContext, "cd_" + dataList.get("fid"), gson.toJson(jsonObject));
    }

    private void insert_WMS_WarehouseEntry_ScanCodeRecord(String billno, AlertDialog dialog) {
        ArrayList<Map> prolists = new ArrayList<>();
        if (detailsList.size() > 0) {
            for (int i = 0; i < detailsList.size(); i++) {
                Map data = new HashMap();
                ArrayList<Map> codelists = new ArrayList<>();
                String erpno = detailsList.get(i).get("erpno") + "";
                data.put("erpno", erpno);
                data.put("std", detailsList.get(i).get("std"));
                String code = "";
                ArrayList<Map> codesupplierList = new ArrayList<>();
                codesupplierList = (ArrayList<Map>) JSON.parseArray(detailsList.get(i).get("codesupplierList") + "", Map.class);
                if (codesupplierList.size() > 0) {
                    code = codesupplierList.get(0).get("code") + "";
                }
                data.put("code", code);
                for (int j = 0; j < codelist.size(); j++) {
                    String erpno2 = codelist.get(j).get("erpno") + "";
                    if (erpno.trim().equals(erpno2.trim())) {
                        Map motorid = new HashMap();
                        motorid.put("motorid", codelist.get(j).get("motorid") + "");
                        codelists.add(motorid);
                    }
                }

                data.put("codelists", codelists);
                prolists.add(data);
            }
        }

        Gson gson = new Gson();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scanner", SPUtils.get(mContext, "U_Name", ""));
        jsonObject.put("scannerid", SPUtils.get(mContext, "U_Id", ""));
        jsonObject.put("billno", dataList.get("id"));
        jsonObject.put("zt", zt);
        jsonObject.put("prolists", prolists);
        jsonObject.put("fid", dataList.get("fid"));
        jsonObject.put("u_erp_account", SPUtils.get(mContext, "U_ERP_ACCOUNT", ""));
        jsonObject.put("repositorycode", repositorycode);//库位编码

        String datStr = gson.toJson(jsonObject);
        datStr = datStr.replaceAll("\\\\", "").trim();

        LogUtils.e("TAG", "datStr:" + datStr);
        HttpClient.getInstance().postData(CommonHttpConsts.insert_WMS_WarehouseEntry_ScanCodeRecord, "insert_WMS_WarehouseEntry_ScanCodeRecord").headers("token", SPUtils.get(mContext, "token", "") + "").upJson(datStr).execute(new HttpCallbackData() {

            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                if (code == 1001) {
                    ToastUtil.show(msg);
                    if (dialog != null) {
                        kuContent = null;
                        dialog.dismiss();
                    }
                    ts_cg();

                    SPUtils.remove(mContext, "cd_" + dataList.get("fid"));

                    Intent data = new Intent();
                    data.putExtra("name", true);
                    setResult(RESULT_OK, data);
                    finish();
                } else if (code == 1004) {
                    ToastUtil.show(msg);
                    if (dialog != null) {
                        kuContent = null;
                        dialog.dismiss();
                    }
                    SPUtils.remove(mContext, "cd_" + dataList.get("fid"));
                    Intent data = new Intent();
                    data.putExtra("name", true);
                    setResult(RESULT_OK, data);
                    finish();
                } else if (code == 1002) {
                    if (dialog != null) {
                        kuContent = null;
                        dialog.dismiss();
                    }
                    ts_cw();
                    exitDialogTi(msg, info);
                } else {
                    ToastUtil.show(msg);
                    ts_cw();
                }
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }
        });
    }

    private boolean isMima = true;

    public void editDialog(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_edit, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        EditText content = v.findViewById(R.id.content);
        TextView tvSave = v.findViewById(R.id.tvSave);
        LinearLayout lyMima = v.findViewById(R.id.lyMima);
        ImageView imgMima = v.findViewById(R.id.imgMima);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());
        if (isMima) {
            isMima = true;
            imgMima.setBackground(getResources().getDrawable(R.mipmap.mima_seletd));
        } else {
            isMima = false;
            imgMima.setBackground(getResources().getDrawable(R.mipmap.mima));
        }
        if (R_Auth_Code.contains("WMS_TASK_IN_YZGZ")) {
            lyMima.setOnClickListener(v12 -> {
                if (isMima) {
                    isMima = false;
                    imgMima.setBackground(getResources().getDrawable(R.mipmap.mima));
                } else {
                    isMima = true;
                    imgMima.setBackground(getResources().getDrawable(R.mipmap.mima_seletd));
                }
            });
        }

        tvSave.setOnClickListener(view -> {
            String contentStr = content.getText().toString().trim();
            if (StringUtils.isEmpty(contentStr)) {
                ToastUtil.show("请输入识别码");
                return;
            }
            if (contentStr.length() != 19 && contentStr.length() != 20) {
                ToastUtil.show("识别码长度有误！");
                return;
            }
            if (codelist.size() >= num) {
                ToastUtil.show("请检查数量！");
                return;
            }

            if (isMima) {
                rule(contentStr, dialog);
            } else {
                int codes = 0;
                if (codelist.size() > 0) {
                    for (int ii = 0; ii < codelist.size(); ii++) {
                        if (codelist.get(ii).get("erpno").toString().contains(detailsList.get(position).get("erpno") + "")) {
                            codes = codes + 1;
                        }
                    }
                }

                int num = StringUtils.isEmpty(detailsList.get(position).get("num") + "") ? 0 : Integer.valueOf(detailsList.get(position).get("num") + "");

                if (codes >= num) {
                    tiDialog("以达到拣货数量，请检查！");
                    ts_cw();
                } else {
                    if (detailsList.size() >= position) {
                        Map data = new HashMap();
                        data.put("billno", dataList.get("lastbillno"));
                        data.put("scaningtime", StringUtils.getTimeS());
                        data.put("scanner", SPUtils.get(mContext, "U_Name", "") + "");
                        data.put("scannerid", SPUtils.get(mContext, "U_Id", "") + "");
                        data.put("sn", StringUtils.getDeviceSN(mContext));
                        data.put("erpno", detailsList.get(position).get("erpno"));
                        data.put("motorid", contentStr);
                        data.put("no", dataList.get("no"));
                        data.put("std", detailsList.get(position).get("std"));

                        data.put("name", detailsList.get(position).get("name"));
                        data.put("brand", detailsList.get(position).get("brand") + "");
                        data.put("car", detailsList.get(position).get("car"));

                        LogUtils.e("TAG", "data:" + data.toString());
                        if (!codelist.toString().contains(contentStr)) {
                            codelist.add(data);
                            ts_cg();

                            ToastUtil.show("添加成功");
                            detailsAdapter.setCode(codelist);
                            codeAdapter.setData(codelist);
                            tvNum.setText("（" + codelist.size() + "）");
                            dialog.dismiss();
                        } else {
                            ToastUtil.show(contentStr + "已添加过");
                            ts_cw();
                        }

                        cun();
                    }
                }
            }
        });
    }

    public void exitDialogTi(String title, String context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_exit2, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvContext = v.findViewById(R.id.tvContext);
        TextView tvName = v.findViewById(R.id.tvName);
        TextView tvSave = v.findViewById(R.id.tvSave);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        tvContext.setMovementMethod(new ScrollingMovementMethod());
        tvName.setText(title);
        if (!StringUtils.isEmpty(context)) {
            String con = context.replace("[", "");
            con = con.replace("]", "");
            con = con.replace(",", "\n");
            tvContext.setText(con);
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());

        tvSave.setOnClickListener(view -> {
            dialog.dismiss();
        });
    }

    private EditText kuContent;
    private String repositorycode = "";

    public void kuweiDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_edit, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        kuContent = v.findViewById(R.id.content);
        TextView tvSave = v.findViewById(R.id.tvSave);
        TextView tvName = v.findViewById(R.id.tvName);
        LinearLayout lyMima = v.findViewById(R.id.lyMima);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        tvName.setText("请确认库位");
        kuContent.setKeyListener(null);
        kuContent.setHint("扫码输入");
        kuContent.requestFocus();
        lyMima.setVisibility(View.GONE);
        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> {
            kuContent = null;
            dialog.dismiss();
        });

        tvSave.setOnClickListener(view -> {
            String contentStr = kuContent.getText().toString().trim();
            if (StringUtils.isEmpty(contentStr)) {
                ToastUtil.show("请输入扫码输入");
                return;
            }
//            if (StringUtils.isFastClick()) {
//                return;
//            }
            repositorycode = contentStr.replace("K:", "").trim();
            exitDialog(4, dialog);
        });
    }
}
